package com.sinog.biz.config.param;

import com.sinog.core.utilbean.Constants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @desc 参数转换注解
 * @author lzq
 * @date -
 */
@Aspect
@Component
public class ConverseAspect {

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.sinog.biz.service..*(..))")
    public void serviceConverse() {
    }

    /**
     * 环绕通知
     * @param joinPoint joinPoint
     * @return Object
     */
    @Around("serviceConverse()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        final Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        // 获取参数的值
        final Object[] args = joinPoint.getArgs();
        //获取参数注解 :1维是参数，2维是注解
        Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
        for(int i = 0; i < annotations.length; i++) {
            Object param = args[i];
            Annotation[] paramAn = annotations[i];
            //参数为空 直接下一个参数
            if(null == param || paramAn.length == Constants.Number.NUM_ZERO) {
                continue;
            }
            for(Annotation annotation : paramAn) {
                //判断是否包含某个制定的注解
                if(annotation.annotationType().equals(Converse.class)) {
                    //效验改参数 验证一次并退出改注解
                    Converse converse = (Converse)annotation;
                    //value是固定值 就是这样写
                    Field field = String.class.getDeclaredField("value");
                    field.setAccessible(true);
                    String newValue = "";
                    if(!Constants.NumberStr.NUM_STR_ZERO.equals(converse.converseTo())){
                        newValue = converse.converseTo();
                    }
                    if(param.toString().equals(converse.caseIf())){
                        field.set(param,field.get(newValue));
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}